//
//  FilteredWebCache.m
//  VietNews
//
//  Created by Nguyen .a.Hph on 7/4/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FilteredWebCache.h"
#import "FilterMgr.h"

@implementation FilteredWebCache

-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request{
     NSURL *url = [request URL];
     BOOL blockURL = [[FilterMgr sharedInstance] shouldBlockURL:url];
     if (blockURL) {
         NSURLResponse *response =
            [[NSURLResponse alloc] initWithURL:url
                                MIMEType:@"text/plain"
                                expectedContentLength:1
                                textEncodingName:nil];
     
         NSCachedURLResponse *cachedResponse =
         [[NSCachedURLResponse alloc] initWithResponse:response
                                                  data:[NSData dataWithBytes:" " length:1]];
     
         [super storeCachedResponse:cachedResponse forRequest:request];
     }
     return [super cachedResponseForRequest:request];
     
    /*
    NSURL *currentURL = [request URL];
    
    NSCachedURLResponse *resp = [super cachedResponseForRequest:request];
    
    if( resp == nil ) {
        NSLog(@"The Resource is MISSING FROM THE WEBCACHE - %@", currentURL.absoluteString);
    } else {
        NSLog(@"Loaded FROM THE WEBCACHE - %@", currentURL.absoluteString);
    }
    
    return resp;
     */
}

+(void)startFilterWebCache{
    NSFileManager *filemgr;
    filemgr =[NSFileManager defaultManager];
    
    //NSArray *dirPaths;
    //NSString *docsDir;
    //dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //NSString *tmpDir = NSTemporaryDirectory();//tmp folder
    //docsDir = [dirPaths objectAtIndex:0];//Documents folder
    //NSLog(@"%@ --- %@",tmpDir,docsDir);
    
    if (![filemgr fileExistsAtPath:@"/tmp/filtercache.dat"])
        [filemgr createFileAtPath:@"/tmp/filtercache.dat" contents:nil attributes:nil];
    
    NSString *path = @"/tmp/filtercache.dat";// the path to the cache file
    NSUInteger discCapacity = 10*1024*1024;
    NSUInteger memoryCapacity = 512*1024;
    
    FilteredWebCache *cache =
    [[FilteredWebCache alloc] initWithMemoryCapacity: memoryCapacity
                                        diskCapacity: discCapacity diskPath:path];
    [NSURLCache setSharedURLCache:cache];
}
+(void)endFilterWebCache{
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
}
@end
